﻿using System.Windows;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using System.Windows.Media;
using Microsoft.Phone.Shell;
using System.Linq;

namespace CuteRibs.MVVMLib
{
	public class ViewBase : PhoneApplicationPage
	{
		private PageViewModelBase viewModel;
		private ApplicationBarIconButton[] appButtons;
		private ApplicationBarMenuItem[] appMenus;

		protected PageViewModelBase ViewModel
		{
			get
			{
				if (this.viewModel == null)
				{
					this.viewModel = this.DataContext as PageViewModelBase;
				}

				return this.viewModel;
			}
		}

		public ApplicationBarIconButton[] AppButtons
		{
			get
			{
				if (this.appButtons == null)
				{
					if (this.ApplicationBar == null || this.ApplicationBar.Buttons == null)
					{
						this.appButtons = new ApplicationBarIconButton[0];
					}
					else
					{
						this.appButtons = this.ApplicationBar.Buttons.OfType<ApplicationBarIconButton>().ToArray();
					}
				}

				return this.appButtons;
			}
		}

		public ApplicationBarMenuItem[] AppMenus
		{
			get
			{
				if (this.appMenus == null)
				{
					if (this.ApplicationBar == null || this.ApplicationBar.MenuItems == null)
					{
						this.appMenus = new ApplicationBarMenuItem[0];
					}
					else
					{
						this.appMenus = this.ApplicationBar.MenuItems.OfType<ApplicationBarMenuItem>().ToArray();
					}
				}

				return this.appMenus;
			}
		}

		public ViewBase()
		{
			this.SetTransition();
			this.FontFamily = (FontFamily)Application.Current.Resources["PhoneFontFamilyNormal"];
			this.FontSize = (double)Application.Current.Resources["PhoneFontSizeNormal"];
			this.Foreground = (Brush)Application.Current.Resources["PhoneForegroundBrush"];
		}

		protected override void OnNavigatedFrom(NavigationEventArgs e)
		{
			base.OnNavigatedFrom(e);

			if (this.ViewModel != null)
			{
				this.ViewModel.OnNavigatedFrom(this, e, this.NavigationContext);
			}
		}

		protected override void OnNavigatedTo(NavigationEventArgs e)
		{
			base.OnNavigatedTo(e);

			if (this.ViewModel != null)
			{
				this.ViewModel.OnNavigatedTo(this, e, this.NavigationContext);
			}
		}

		protected virtual void SetTransition()
		{
			var element = this;
			var inTransition = new NavigationInTransition()
			{
				Backward = new TurnstileTransition() { Mode = TurnstileTransitionMode.BackwardIn },
				Forward = new TurnstileTransition() { Mode = TurnstileTransitionMode.ForwardIn },
			};

			var outTransition = new NavigationOutTransition()
			{
				Backward = new TurnstileTransition() { Mode = TurnstileTransitionMode.BackwardOut },
				Forward = new TurnstileTransition() { Mode = TurnstileTransitionMode.ForwardOut },
			};

			TransitionService.SetNavigationInTransition(element, inTransition);
			TransitionService.SetNavigationOutTransition(element, outTransition);
		}
	}
}
